var DBUtils = require("./mysqlManage");
var Graph = require("../Utils/getGraph.js");
var Path = require("../Utils/FindPath.js");

/**
 * 获取所有城市
 * 传入参数：{}
 * 返回参数：Array [{id:...,//城市id name:...,//城市名}...]
 * @param {*} request 
 * @param {*} response 
 */
let getAllCity = function(request,response){ 
	// console.log("进入getAllCity方法")
    let sql = "select * from city";
    DBUtils.query(sql,(data)=>{ 
        response.json(data);
    });
}

// let getPaths = function(request,response){ 
// 	let sql = "select * from path";
// 	DBUtils.query(sql,(data)=>{ 
// 	    response.json(data);
// 	});
// }


/**
 * 功能：获取两个城市间的所有可能路径
 * 传入参数：{start:...//出发城市名,end:...//目的城市名},
 * 返回：Array[ { len:...//路径长度, path:[...]//路径，记录路径上的城市名, price:...//旅途费用 },{},... ]
 * @param {Object} request
 * @param {Object} response
 */
let getCityPath = function(request,response){ 
	let data = request.body;
	// console.log("data = ",data);
	let startCity = data.start;
	let endCity = data.end;
	
	
	let sql = "select * from city";
	DBUtils.query(sql,(data)=>{ 
	    let citys = data;
	    let start;
	    let end;
	    for(let i = 0; i < citys.length;i++){ 
	    	if(startCity == citys[i].name){ 
	    		start = i;
	    		break;
	    	}
	    }
	    
	    for(let i = 0; i < citys.length;i++){
	    	if(endCity == citys[i].name){ 
	    		end = i;
	    		break;
	    	}
	    }
		// console.log("start = ",start)
		// console.log("end = ",end);
		let sql = "select * from path";
		DBUtils.query(sql,(data)=>{ 
		    let cityPath = data;
			// console.log("cityPath = ",cityPath);
			//计算邻接矩阵
		    let graph = Graph.getGraph(citys,cityPath);
			// console.log("graph = ",graph);
			// console.log("start = ",start);
			// console.log("end = ",end);
			//深度优先搜索获取两个城市间的路径
		    let resPath = Path.PathsSourceTarget(graph,start,end);
			for(let i = 0; i < resPath.length;i++){ 
				for(let j = 0; j < resPath[i].path.length;j++){ 
					let id = resPath[i].path[j];
					resPath[i].path[j] = citys[id].name;
				}
			} 
			// console.log("resPath",resPath);
		    response.json(resPath);
		});
	
	});

}
module.exports.getCityPath = getCityPath;
module.exports.getAllCity = getAllCity;